<template>
    <div class="app-container">

        <!-- 查询条件 -->
        <el-card>
            <el-form ref="dictTypeRef" :inline="true" :model="queryParams" label-width="68px">
                <el-form-item label="字典名称" prop="dictName">
                    <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="字典类型" prop="dictType">
                    <el-input v-model="queryParams.dictType" placeholder="请输入字典类型" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="字典状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="字典状态" clearable>
                        <el-option
v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="创建时间" style="width: 308px">
                    <el-date-picker
v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格 结果展示 -->
        <el-card style="margin-top: 20px;">

            <template #header>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button
v-hasPermi="['system:dict:add']" type="primary" plain icon="Plus"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
v-hasPermi="['system:dict:edit']" type="success" plain icon="Edit" :disabled="single"
                            @click="handleUpdate()">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
v-hasPermi="['system:dict:remove']" type="danger" plain icon="Delete"
                            :disabled="multiple" @click="handleDelete()">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
v-hasPermi="['system:dict:export']" type="warning" plain icon="Download"
                            @click="handleExport">导出</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
v-hasPermi="['system:dict:remove']" type="danger" plain
 icon="Refresh"
                            @click="handleRefreshCache">刷新缓存</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table
v-loading="loading" :data="pageData.rows" style="width: 100%"
                @selectionChange="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="字典主键" align="center" prop="dictId" />
                <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
                <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
                        <template #default="scope">
                          <router-link :to="'/system/dict-data/index/' + scope.row.dictId" class="link-type">
                            <span>{{ scope.row.dictType }}</span>
                          </router-link>
                        </template>
                      </el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                    <template #default="scope">
                        <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
                <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{parseTime(scope.row.createTime)}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button
v-hasPermi="['system:dict:edit']" circle type="primary" icon="Edit"
                            @click="handleUpdate(scope.row)" />
                        <el-button
v-hasPermi="['system:dict:remove']" circle type="danger" icon="Delete"
                            @click="handleDelete(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
            <pagination
v-show="pageData.total > 0" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" :total="pageData.total" @pagination="getList" />
        </el-card>

        <!-- 新增修改对话框  -->
        <el-dialog v-model="open" :title="title" width="500" :close-on-click-modal="false">
            <el-form ref="editRef" :model="form" label-width="80px">
                <el-form-item
label="字典名称" prop="dictName"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.dictName" placeholder="请输入字典名称" />
                </el-form-item>

                <el-form-item
label="字典类型" prop="dictType"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.dictType" placeholder="请输入字典类型" />
                </el-form-item>

                <el-form-item
label="状态" prop="status"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                                      dict.label
                                  }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Dict" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { SysDictTypeQueryReq, FormReq, SysDictTypeResp } from '@/types/dictType';
import { listType, getType, addType, updateType, delType,refreshCache  } from '@/api/system/dict/type';
import { parseTime } from '@/utils/ruoyi';
import type { FormInstance } from 'element-plus';
// 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = proxy!.useDict('sys_normal_disable');

// 响应式对象
const dateRange = ref<any[]>([]);
const loading = ref<boolean>(false);

const single = ref<boolean>(true);
const multiple = ref<boolean>(true);
const showSearch = ref<boolean>(true);
const mutilSelection = ref<SysDictTypeResp[]>([]);
const ids = ref<number[]>([]);

// 对话框配置
const open = ref(false);
const title = ref('');

// 得到验证对象
const editRef = ref<FormInstance>();

// 分页数据
const pageData = reactive<{
        total : number;
        rows : SysDictTypeResp[]
    }>({
        total: 0,
        rows: []
    });

// 响应式代理模型
const data = reactive<{
        form : FormReq;
        queryParams : SysDictTypeQueryReq;
    }>({
        form: {
            dictId: undefined,
            dictName: '',
            dictType: '',
            status: '',
            remark: ''
        },
        queryParams: {
            dictName: '',
            dictType: '',
            status: '',
            pageNum: 1,
            pageSize: 10
        }
    });

// 代理模型转为相应模型
const { queryParams, form } = toRefs(data);

// 重置
function resetQuery() {
    dateRange.value = [];
    proxy?.resetForm('dictTypeRef');
    handleQuery();
}

// 查询
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

// 分页查询
function getList() {
    loading.value = true;

    // 添加日期值
    listType(proxy?.addDateRange(queryParams.value, dateRange.value)).then((resp : any) => {
        pageData.total = resp.data.total;
        pageData.rows = resp.data.list;
        loading.value = false;
    });
}

// 新增
function handleAdd() {
    reset();
    title.value = '字典管理--新增';
    open.value = true;
}

// 修改
function handleUpdate(row ?: null | SysDictTypeResp) {
    let primaryKey : number;
    if (row) {
        primaryKey = row.dictId;
    } else {
        primaryKey = ids.value[0];
    }
    // 重置表单
    reset();

    // 根据id查询
    getType(primaryKey).then((resp : any) => {
        form.value = resp.data;
        title.value = '字典管理--修改';
        open.value = true;
    });
}

// 多选框选中数据
function handleSelectionChange(selection : SysDictTypeResp[]) {
    mutilSelection.value = selection;
    ids.value = selection.map(row => row.dictId);
    // 修改按钮 禁用 判断
    single.value = selection.length !== 1;
    // 删除按钮 禁用 判断
    multiple.value = selection.length === 0;
}

// 删除 或 禁用
function handleDelete(row ?: SysDictTypeResp) {
    let primaryKeys : any;
    if (row) {
        primaryKeys = row.dictId;
    } else {
        primaryKeys = ids.value;
    }

    proxy?.$modal
        .confirm('是否确认删除参数编号为"' + primaryKeys + '"的数据项？')
        .then(function () {
            return delType(primaryKeys);
        })
        .then(() => {
            getList();
                proxy!.$modal.msgSuccess('删除成功');
        })
        .catch((e : any) => {
            console.log(e);
        });
}

// 导出
function handleExport(){
    let queryData : any = {};
    // 根据勾选行下载
    if (ids.value && ids.value.length > 0) {
        queryData.ids = ids.value.join();
    } else {
        queryData = {
            ...queryParams.value
        };
    }

    proxy?.download(
        'admin/dict/type/export',
        queryData,
        `dicttype_${new Date().getTime()}.xlsx`
    );
}

// 新增 或 修改 提交按钮
async function submitForm() {
    if (!editRef.value) {
        return;
    }
    await editRef.value.validate((valid : boolean, fields : any) => {
        if (valid) {
            // 调用 修改请求
            if (form.value.dictId) {
                updateType(form.value).then(() => {
                    proxy?.$modal.msgSuccess('修改成功');
                    open.value = false;
                    getList();
                });
            } else {
                //调用 新增请求
                addType(form.value).then(() => {
                    proxy?.$modal.msgSuccess('新增成功');
                    open.value = false;
                    getList();
                });
            }

        } else {
            console.log('error submit!', fields);
        }
    });
}

// 新增或修改 对话框取消按钮
function cancel() {
    open.value = false;
}

// 表单重置
function reset() {
    form.value = {
        dictId: undefined,
        dictName: '',
        dictType: '',
        status: '',
        remark: ''
    };
    // 重置表单样式
    proxy?.resetForm('editRef');
}

/** 刷新缓存按钮操作 */
function  handleRefreshCache() {
    refreshCache().then(() => {
        proxy?.$modal.msgSuccess('刷新成功');
        proxy?.$store.dispatch('dict/cleanDict');
    });
}

// 初始化查询
getList();
</script>
